package com.pgm.service.impl;

import com.pgm.dao.IndexMapper;
import com.pgm.model.UserInfo;
import com.pgm.service.IndexService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.RegionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class IndexServiceImpl implements IndexService {


    // 装置
    @Value("${plantinObjectIds}")
    public String plantinObjectIds;
    @Value("${plantoutObjectIds}")
    public String plantoutObjectIds;

    // Cob
    @Value("${cobinObjectIds}")
    public String cobinObjectIds;
    @Value("${coboutObjectIds}")
    public String coboutObjectIds;

    // 承包商
    @Value("${contractorinObjectIds}")
    public String contractorinObjectIds;
    @Value("${contractoroutObjectIds}")
    public String contractoroutObjectIds;

    @Value("${contractorSDepartment}")
    public String contractorSDepartment;

    @Value("${employeeDepartment}")
    public String employeeDepartment;


    @Autowired
    IndexMapper indexMapper;


    // cob
    @Override
    public List<UserInfo> cob(String userNoOrUsername) {
        ArrayList<String> objects = new ArrayList<>();
        objects.addAll(Arrays.asList(contractorSDepartment.split(",")));
        objects.addAll(Arrays.asList(employeeDepartment.split(",")));
        ArrayList<String> deviceIds = new ArrayList<>();
        deviceIds.addAll(Arrays.asList(cobinObjectIds.split(",")));
        deviceIds.addAll(Arrays.asList(coboutObjectIds.split(",")));
        List<UserInfo> userList = indexMapper.getUserList(objects, Arrays.asList(cobinObjectIds.split(",")), Arrays.asList(coboutObjectIds.split(",")), deviceIds);
        LocalDateTime now = LocalDateTime.now();
        userList.stream().forEach(p -> {
            if (p.getInTime() != null && !"".equals(p.getInTime())) {
                LocalDateTime localDate1 = LocalDateTime.parse(p.getInTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"));
                long until = localDate1.until(now, ChronoUnit.HOURS);
                if (until >= 5) {
                    p.setIntervals((int) until);
                } else {
                    p.setIntervals(0);
                }
            }
        });
        return userList.stream().sorted(Comparator.comparing(UserInfo::getIntervals).reversed()).collect(Collectors.toList());
    }


    public static void main(String[] args) {

        LocalDateTime localDate1 = LocalDateTime.parse("2021-11-02 12:49:31.0", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS"));
    }

    // 装置
    @Override
    public List<UserInfo> device(String userNoOrUsername) {

        ArrayList<String> objects = new ArrayList<>();
        objects.addAll(Arrays.asList(contractorSDepartment.split(",")));
        objects.addAll(Arrays.asList(employeeDepartment.split(",")));
        ArrayList<String> deviceIds = new ArrayList<>();
        deviceIds.addAll(Arrays.asList(plantinObjectIds.split(",")));
        deviceIds.addAll(Arrays.asList(plantoutObjectIds.split(",")));

        List<UserInfo> userList = indexMapper.getUserList(objects, Arrays.asList(plantinObjectIds.split(",")), Arrays.asList(plantoutObjectIds.split(",")), deviceIds);
        LocalDateTime now = LocalDateTime.now();
        userList.stream().forEach(p -> {
            if (p.getInTime() != null && !"".equals(p.getInTime())) {
                LocalDateTime localDate1 = LocalDateTime.parse(p.getInTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"));
                long until = localDate1.until(now, ChronoUnit.HOURS);
                if (until >= 5) {
                    p.setIntervals((int) until);
                } else {
                    p.setIntervals(0);
                }
            }
        });
        return userList.stream().sorted(Comparator.comparing(UserInfo::getIntervals).reversed()).collect(Collectors.toList());

    }


    // 休息区
    @Override
    public List<UserInfo> restArea(String userNoOrUsername) {
        ArrayList<String> objects = new ArrayList<>();
        objects.addAll(Arrays.asList(contractorSDepartment.split(",")));
        objects.addAll(Arrays.asList(employeeDepartment.split(",")));
        ArrayList<String> deviceIds = new ArrayList<>();
        deviceIds.addAll(Arrays.asList(contractorinObjectIds.split(",")));
        deviceIds.addAll(Arrays.asList(contractoroutObjectIds.split(",")));
        List<UserInfo> userList = indexMapper.getUserList(objects, Arrays.asList(contractorinObjectIds.split(",")), Arrays.asList(contractoroutObjectIds.split(",")), deviceIds);
        LocalDateTime now = LocalDateTime.now();
        userList.stream().forEach(p -> {
            if (p.getInTime() != null && !"".equals(p.getInTime())) {
                LocalDateTime localDate1 = LocalDateTime.parse(p.getInTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"));
                long until = localDate1.until(now, ChronoUnit.HOURS);
                if (until >= 12) {
                    p.setIntervals((int) until);
                } else {
                    p.setIntervals(0);
                }
            }
        });
        return userList.stream().sorted(Comparator.comparing(UserInfo::getIntervals).reversed()).collect(Collectors.toList());


    }

    @Override
    public UserInfo getUserInfoById(String id) {

        return indexMapper.getUserInfoById(id);
    }


    @Override
    public Map<String, Integer> peopleCounting() {

        ArrayList<String> cobDeviceIds = new ArrayList<>();
        cobDeviceIds.addAll(Arrays.asList(cobinObjectIds.split(",")));
        cobDeviceIds.addAll(Arrays.asList(coboutObjectIds.split(",")));
        Integer cobEmployees = indexMapper.peopleCounting(Arrays.asList(employeeDepartment.split(",")), Arrays.asList(cobinObjectIds.split(",")), Arrays.asList(coboutObjectIds.split(",")), cobDeviceIds);
        Integer cobContractor = indexMapper.peopleCounting(Arrays.asList(contractorSDepartment.split(",")), Arrays.asList(cobinObjectIds.split(",")), Arrays.asList(coboutObjectIds.split(",")), cobDeviceIds);

        ArrayList<String> plantDeviceIds = new ArrayList<>();
        plantDeviceIds.addAll(Arrays.asList(plantinObjectIds.split(",")));
        plantDeviceIds.addAll(Arrays.asList(plantoutObjectIds.split(",")));
        Integer plantEmployees = indexMapper.peopleCounting(Arrays.asList(employeeDepartment.split(",")), Arrays.asList(plantinObjectIds.split(",")), Arrays.asList(plantoutObjectIds.split(",")), plantDeviceIds);
        Integer plantContractor = indexMapper.peopleCounting(Arrays.asList(contractorSDepartment.split(",")), Arrays.asList(plantinObjectIds.split(",")), Arrays.asList(plantoutObjectIds.split(",")), plantDeviceIds);

        ArrayList<String> contractorDeviceIds = new ArrayList<>();
        contractorDeviceIds.addAll(Arrays.asList(contractorinObjectIds.split(",")));
        contractorDeviceIds.addAll(Arrays.asList(contractoroutObjectIds.split(",")));
        Integer contractorEmployees = indexMapper.peopleCounting(Arrays.asList(employeeDepartment.split(",")), Arrays.asList(contractorinObjectIds.split(",")), Arrays.asList(contractoroutObjectIds.split(",")), contractorDeviceIds);
        Integer contractorContractor = indexMapper.peopleCounting(Arrays.asList(contractorSDepartment.split(",")), Arrays.asList(contractorinObjectIds.split(",")), Arrays.asList(contractoroutObjectIds.split(",")), contractorDeviceIds);
        Map<String, Integer> result = new HashMap<>(10);
        result.put("totol", cobEmployees + cobContractor + plantEmployees + plantContractor + contractorEmployees + contractorContractor);
        result.put("cobTotol", cobEmployees + cobContractor);
        result.put("cobEmployees", cobEmployees);
        result.put("cobContractor", cobContractor);
        result.put("plantTotol", plantEmployees + plantContractor);
        result.put("plantEmployees", plantEmployees);
        result.put("plantContractor", plantContractor);
        result.put("ontractorTotol", contractorEmployees + contractorContractor);
        result.put("contractorEmployees", contractorEmployees);
        result.put("contractorContractor", contractorContractor);
        return result;
    }

    @Override
    public HSSFWorkbook exportExcel() {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("sheet1");
        sheet.setColumnWidth(0, 20 * 256);
        sheet.setColumnWidth(1, 20 * 256);
        sheet.setColumnWidth(2, 30 * 256);
        sheet.setColumnWidth(3, 20 * 256);
        HSSFCellStyle titleStyle = workbook.createCellStyle();        //主标题样式
        titleStyle(workbook, titleStyle);

        HSSFCellStyle titleStyleVice = workbook.createCellStyle();        //副标题样式
        titleStyleVice(workbook, titleStyleVice);

        HSSFCellStyle style = workbook.createCellStyle();
        HSSFFont font = workbook.createFont();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style.setFont(font);
        style.setBorderTop(CellStyle.BORDER_THIN);
        style.setBorderRight(CellStyle.BORDER_THIN);
        style.setBorderBottom(CellStyle.BORDER_THIN);
        style.setBorderLeft(CellStyle.BORDER_THIN);

        int rowNum = 0;


        ArrayList<String> cobDeviceIds = new ArrayList<>();
        cobDeviceIds.addAll(Arrays.asList(cobinObjectIds.split(",")));
        cobDeviceIds.addAll(Arrays.asList(coboutObjectIds.split(",")));
        List<UserInfo> employee = indexMapper.getUserList(Arrays.asList(employeeDepartment.split(",")), Arrays.asList(cobinObjectIds.split(",")), Arrays.asList(coboutObjectIds.split(",")), cobDeviceIds);
        List<UserInfo> contractor = indexMapper.getUserList(Arrays.asList(contractorSDepartment.split(",")), Arrays.asList(cobinObjectIds.split(",")), Arrays.asList(coboutObjectIds.split(",")), cobDeviceIds);

        rowNum = getCobRowNum(sheet, titleStyle, titleStyleVice, style, rowNum, "cob", employee, contractor,workbook);


        ArrayList<String> plantDeviceIds = new ArrayList<>();
        plantDeviceIds.addAll(Arrays.asList(plantinObjectIds.split(",")));
        plantDeviceIds.addAll(Arrays.asList(plantoutObjectIds.split(",")));
        List<UserInfo> employee1 = indexMapper.getUserList(Arrays.asList(employeeDepartment.split(",")), Arrays.asList(plantinObjectIds.split(",")), Arrays.asList(plantoutObjectIds.split(",")), plantDeviceIds);
        List<UserInfo> contractor1 = indexMapper.getUserList(Arrays.asList(contractorSDepartment.split(",")), Arrays.asList(plantinObjectIds.split(",")), Arrays.asList(plantoutObjectIds.split(",")), plantDeviceIds);

        rowNum = getCobRowNum(sheet, titleStyle, titleStyleVice, style, rowNum, "装置", employee1, contractor1,workbook);

        ArrayList<String> contractorDeviceIds = new ArrayList<>();
        contractorDeviceIds.addAll(Arrays.asList(contractorinObjectIds.split(",")));
        contractorDeviceIds.addAll(Arrays.asList(contractoroutObjectIds.split(",")));

        List<UserInfo> employee2 = indexMapper.getUserList(Arrays.asList(employeeDepartment.split(",")), Arrays.asList(contractorinObjectIds.split(",")), Arrays.asList(contractoroutObjectIds.split(",")), contractorDeviceIds);
        List<UserInfo> contractor2 = indexMapper.getUserList(Arrays.asList(contractorSDepartment.split(",")), Arrays.asList(contractorinObjectIds.split(",")), Arrays.asList(contractoroutObjectIds.split(",")), contractorDeviceIds);

        rowNum = getCobRowNum(sheet, titleStyle, titleStyleVice, style, rowNum, "承包商休息区", employee2, contractor2,workbook);


        return workbook;
    }

    private int getCobRowNum(HSSFSheet sheet, HSSFCellStyle titleStyle, HSSFCellStyle titleStyleVice, HSSFCellStyle style, int rowNum, String titleName, List<UserInfo> userInfo, List<UserInfo> userInfo2,HSSFWorkbook workbook) {
        HSSFRow cobRow = sheet.createRow(rowNum);

        HSSFCell cell0 = cobRow.createCell(0);
        // 合并单元格CellRangeAddress构造参数依次表示起始行，截至行，起始列， 截至列
        CellRangeAddress address = new CellRangeAddress(rowNum, rowNum, 0, 3);
        sheet.addMergedRegion(address);
        titleStyle(sheet, workbook, address);
//        cobRow.setRowStyle(titleStyle);
        // 设置单元格内容
        cell0.setCellValue(titleName);
        cell0.setCellStyle(titleStyle);
        rowNum = rowNum + 1;
        HSSFRow cobRow1 = sheet.createRow(rowNum);

        HSSFCell cell01 = cobRow1.createCell(0);
        // 合并单元格CellRangeAddress构造参数依次表示起始行，截至行，起始列， 截至列
        CellRangeAddress rangeAddress = new CellRangeAddress(rowNum, rowNum, 0, 3);
        sheet.addMergedRegion(rangeAddress);
        titleStyle(sheet, workbook, rangeAddress);
        // 设置单元格内容
        cell01.setCellValue("员工");
        cell01.setCellStyle(titleStyleVice);
        rowNum = rowNum + 1;
        HSSFRow cobRow2 = sheet.createRow(rowNum);
        createCell(style, cobRow2);
        rowNum = rowNum + 1;
        rowNum = creteCellInfo(sheet, style, userInfo, rowNum);

        HSSFRow cobRow3 = sheet.createRow(rowNum);
        HSSFCell cell02 = cobRow3.createCell(0);
        // 合并单元格CellRangeAddress构造参数依次表示起始行，截至行，起始列， 截至列
        CellRangeAddress cellRangeAddress = new CellRangeAddress(rowNum, rowNum, 0, 3);
        sheet.addMergedRegion(cellRangeAddress);
        titleStyle(sheet, workbook, cellRangeAddress);
        // 设置单元格内容
        cell02.setCellValue("承包商");
        cell02.setCellStyle(titleStyleVice);
        rowNum = rowNum + 1;
        HSSFRow cobRow4 = sheet.createRow(rowNum);
        createCell(style, cobRow4);
        rowNum = rowNum + 1;
        rowNum =  creteCellInfo(sheet, style, userInfo2, rowNum);

        return rowNum;
    }

    private void titleStyle(HSSFSheet sheet, HSSFWorkbook workbook, CellRangeAddress address) {
        RegionUtil.setBorderBottom(1, address, sheet, workbook); // 下边框

        RegionUtil.setBorderLeft(1, address, sheet, workbook); // 左边框

        RegionUtil.setBorderRight(1, address, sheet, workbook); // 有边框

        RegionUtil.setBorderTop(1, address, sheet, workbook); // 上边框//输出到本地
    }

    private Integer creteCellInfo(HSSFSheet sheet, HSSFCellStyle style, List<UserInfo> cellvisitorUserInfo, int rowNum) {
        for (UserInfo userInfo : cellvisitorUserInfo) {
            HSSFRow row2 = sheet.createRow(rowNum);
            HSSFCell cell2 = row2.createCell(0);
            cell2.setCellValue(userInfo.getUserName());
            cell2.setCellStyle(style);
            cell2 = row2.createCell(1);
            cell2.setCellValue(userInfo.getCompany());
            cell2.setCellStyle(style);
            cell2 = row2.createCell(2);
            cell2.setCellValue(userInfo.getInTime());
            cell2.setCellStyle(style);
            cell2 = row2.createCell(3);
            cell2.setCellValue(userInfo.getName());
            cell2.setCellStyle(style);
            rowNum = rowNum + 1;
        }
        return  rowNum;
    }


    private void createCell(HSSFCellStyle style, HSSFRow row) {
        HSSFCell cell;
        cell = row.createCell(0);
        cell.setCellValue("用户名");
        cell.setCellStyle(style);

        cell = row.createCell(1);
        cell.setCellValue("部门");
        cell.setCellStyle(style);
        cell = row.createCell(2);
        cell.setCellValue("入场时间");
        cell.setCellStyle(style);
        cell = row.createCell(3);
        cell.setCellValue("门禁位置");
        cell.setCellStyle(style);
    }

    private void titleStyleVice(HSSFWorkbook workbook, HSSFCellStyle titleStyleVice) {
        titleStyleVice.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        titleStyleVice.setVerticalAlignment(HSSFCellStyle.ALIGN_CENTER);
        Font ztFont2 = workbook.createFont();
        ztFont2.setItalic(false);                     // 设置字体为斜体字
        ztFont2.setColor(Font.COLOR_NORMAL);            // 将字体设置为“红色”
        ztFont2.setFontHeightInPoints((short) 14);    // 将字体大小设置为18px
        ztFont2.setFontName("宋体");             // 将“宋体”字体应用到当前单元格上//加粗
        titleStyleVice.setFont(ztFont2);

        titleStyleVice.setBorderTop(CellStyle.BORDER_THIN);
        titleStyleVice.setBorderRight(CellStyle.BORDER_THIN);
        titleStyleVice.setBorderBottom(CellStyle.BORDER_THIN);
        titleStyleVice.setBorderLeft(CellStyle.BORDER_THIN);
    }

    private void titleStyle(HSSFWorkbook workbook, HSSFCellStyle titleStyle) {
        titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        titleStyle.setVerticalAlignment(HSSFCellStyle.ALIGN_CENTER);
        Font ztFont = workbook.createFont();
        ztFont.setItalic(false);                     // 设置字体为斜体字
        ztFont.setColor(Font.COLOR_NORMAL);            // 将字体设置为“红色”
        ztFont.setFontHeightInPoints((short) 18);    // 将字体大小设置为18px
        ztFont.setFontName("宋体");             // 将“宋体”字体应用到当前单元格上//加粗
        titleStyle.setFont(ztFont);
        titleStyle.setBorderTop(CellStyle.BORDER_THIN);
        titleStyle.setBorderRight(CellStyle.BORDER_THIN);
        titleStyle.setBorderBottom(CellStyle.BORDER_THIN);
        titleStyle.setBorderLeft(CellStyle.BORDER_THIN);
    }

}

